//
//  LXRTextView-Extension.swift
//  表情键盘
//
//  Created by MACBOOK on 16/10/19.
//  Copyright © 2016年 刘袭锐. All rights reserved.
//

import UIKit

extension UITextView{
    
    /// 获取textView属性字符串,对应的表情字符串
    func getEmoticonString() -> String {
        // 1.获取属性字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        
        // 2.遍历属性字符串
        let range = NSRange(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? LXREmoticonAttachment {
                attrMStr.replaceCharacters(in: range, with: attachment.chs!)
            }
        }
        
        // 3.获取字符串
        return attrMStr.string
    }
    
    
    /// 给textView插入表情
    func insertEmoticon(emoticon : Emoticon) {
        //1.空白表情
        if emoticon.isEmpty {
            return
        }
        
        //2.删除表情按钮
        if emoticon.isRemove {
            //2.1TextView系统提供便利方法删除
            deleteBackward()
            return
        }
        
        //3.emoji表情
        if emoticon.emojiCode != nil {
            //3.1获取光标位置UITextRange
            let textViewRange = selectedTextRange!
            //3.2插入表情
            replace(textViewRange, withText: emoticon.emojiCode!)
            return
        }
        
        //4.插入其他Image表情
        //4.1根据图片路径创建字符串
        let attachment = LXREmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        let font = self.font!
        attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        let attrImageStr = NSAttributedString(attachment: attachment)
        //4.2创建可变的属性字符串
        let attrMutableStr = NSMutableAttributedString(attributedString: attributedText)
        //4.3将图片属性字符串,替换到可变属性字符串的摸一个位置
        //4.3.1 获取光标位置
        let range = selectedRange
        //4.3.2 替换属性字符串
        attrMutableStr.replaceCharacters(in: range, with: attrImageStr)
        
        //5.显示属性字符串
        attributedText = attrMutableStr
        

/* 解决bug设置 */
        //6.将位子大小设置回原来大小(切记!!!)
        self.font = font
        //7.将光标设置回原来的位置 + 1
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }

    
}

